package db

import (
	"errors"
	"hr/api/dto"

	"github.com/spf13/cast"
	"gorm.io/gorm"
)

type ApplicationManage struct {
	AppModel
	Name              string `gorm:"size:64" json:"name"`
	Job               uint   `gorm:"size:64" json:"job"`
	Phone             string `gorm:"size:255" json:"phone"`
	InviteTime        string `gorm:"size:255" json:"invite_time"`
	CreateBy          string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy          string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark            string `gorm:"size:255" json:"remark"`   //备注
	Status            string `gorm:"size:64;" json:"status"`
	User              `gorm:"-" json:"user"`
	RecruitmentManage `gorm:"-" json:"work"`
}

func (m *ApplicationManage) TableName() string {
	return "application_manage"
}

type ApplicationManagePageModel struct {
	Total    int64               `json:"total"`
	Result   []ApplicationManage `json:"result"`
	PageNo   int                 `json:"pageNo"`
	PageSize int                 `json:"pageSize"`
}

func GetApplicationManagePaging(pagination dto.Pagination, name string) (ApplicationManagePageModel, error) {
	result := ApplicationManagePageModel{
		Total:    0,
		Result:   make([]ApplicationManage, 0),
		PageNo:   pagination.PageNo,
		PageSize: pagination.PageSize,
	}
	offset := (pagination.PageNo - 1) * pagination.PageSize
	dbs := GetInstance().Model(&ApplicationManage{})

	if err := dbs.Offset(offset).Limit(pagination.PageSize).Find(&result.Result).Error; err != nil {
		return result, err
	}
	if err := dbs.Offset(-1).Limit(-1).Count(&result.Total).Error; err != nil {
		return result, err
	}

	for i, manage := range result.Result {
		u, _, _ := GetUsers(map[string]interface{}{
			"id": manage.CreateBy,
		})
		result.Result[i].User = u
		j, _, _ := GetRecruitment(map[string]interface{}{
			"id": manage.Job,
		})
		result.Result[i].RecruitmentManage = j
	}

	return result, nil
}

// GetApplicationManage 根据条件查找
func GetApplicationManage(p map[string]interface{}) (ApplicationManage, error, string) {
	f := ApplicationManage{}
	err := GetInstance().Where(p).First(&f).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func GetLatestApplicationByUserId(userId uint) ApplicationManage {
	f := ApplicationManage{}
	GetInstance().Where("create_by = ?", userId).Order("created_at desc").First(&f)
	return f
}

func CheckExistByUserIdAndJob(userId uint, job uint) (bool, error) {
	var count int64
	f := ApplicationManage{}
	err := GetInstance().Model(&f).Select("job").Where("create_by = ? AND job = ?", userId, job).Count(&count).Error
	return count > 0, err
}

func CreateApplicationManage(p dto.ApplicationManageRequest, user string) (ApplicationManage, error) {
	d := ApplicationManage{
		Job:        p.JobId,
		Phone:      "",
		InviteTime: p.InviteTime,
		CreateBy:   user,
		Status:     "1",
	}
	if err := GetInstance().Create(&d).Error; err != nil {
		return d, err
	}
	return d, nil
}

func UpdateApplicationManage(id uint, p dto.ApplicationManageRequest, userId string) (ApplicationManage, error) {
	f := ApplicationManage{
		AppModel: AppModel{
			ID: id,
		},
	}
	err := GetInstance().Model(&f).Updates(ApplicationManage{
		Job:        p.JobId,
		InviteTime: p.InviteTime,
		UpdateBy:   userId,
		Status:     p.Status,
	}).Updates(map[string]interface{}{
		"id": id,
	}).Scan(&f).Error
	if err != nil {
		return f, err
	}
	if p.Status != "" {
		_, _ = UpdateInviteManage(cast.ToString(id), p.Status)
	}

	if p.Status == "4" {
		GetInstance().Where("id=?", id).First(&f)
		var rec RecruitmentManage
		GetInstance().Where("id=?", f.Job).First(&rec)
		//默认角色
		var role Role
		GetInstance().Where("code='staff'").First(&role)

		GetInstance().Table("user").Where("id=?", f.CreateBy).Updates(map[string]interface{}{"is_staff": "4", "dept_id": rec.Dept, "role_id": role.ID})
	}

	return f, nil
}

func DeleteApplicationManage(id uint) (ApplicationManage, error) {
	f := ApplicationManage{}
	err := GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}
